package com.example.hybridmobiledemo.util;

import android.os.Handler;
import android.os.Looper;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ClassName: OkHttpUtils$
 * @Description: 网络数据访问封装
 * @Author: letquit
 * @CreateDate: 21/10/2021$
 * @Version: 1.0
 */
public class OkHttpUtils {
    private static volatile OkHttpClient okHttpClient = null;
    private Map<String, String> paramMap;
    private String url;
    private Request.Builder request;
    private String host = "http://smartcity.lenovoedu.com/";

    /*
     *初始化OkHttpClient
     */
    private OkHttpUtils() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .build();
        }
    }

    /*
     *创建OkHttpUtils
     */
    public static OkHttpUtils builder() {
        return new OkHttpUtils();
    }

    /*
     *添加url
     */

    public OkHttpUtils url(String api) {
        this.url = host + api;
        return this;
    }

    /*
     *添加参数
     */
    public OkHttpUtils addParam(String key, String value) {
        if (paramMap == null) {
            paramMap = new LinkedHashMap<>();
        }
        paramMap.put(key, value);
        return this;
    }

    /*
     *初始化get方法
     */
    public OkHttpUtils get() {
        request = new Request.Builder().get();
        StringBuilder urlBuffer = new StringBuilder(url);
        if (paramMap != null) {
            urlBuffer.append("?");
            try {
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    urlBuffer.append(URLEncoder.encode(entry.getKey(), "utf-8"))
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), "utf-8"))
                            .append("&");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            urlBuffer.deleteCharAt(urlBuffer.length() - 1);
        }
        request.url(urlBuffer.toString());
        return this;
    }

    /**
     * 自定义一个接口回调
     */
    public interface AsyncCallBack {
        void onResponse(String json);
        void onFailure(Exception e);
    }

    private static Handler handler = new Handler(Looper.getMainLooper());

    /**
     * 异步请求，带有接口回调
     */
    public void async(AsyncCallBack callBack) {
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                assert response.body() != null;
                final String json = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onResponse(json);
                    }
                });
            }
        });
    }
}
